package com.imooc.service.impl;

import com.imooc.converter.OrderMaster2OrderDTOConverter;
import com.imooc.dataobject.OrderDetail;
import com.imooc.dataobject.OrderMaster;
import com.imooc.dataobject.ProductInfo;
import com.imooc.dto.CartDTO;
import com.imooc.dto.OrderDTO;
import com.imooc.enums.OrderStatusEnum;
import com.imooc.enums.PayStatusEnum;
import com.imooc.enums.ResultEnum;
import com.imooc.exception.SellException;
import com.imooc.repository.OrderDetailRepository;
import com.imooc.repository.OrderMasterRepository;
import com.imooc.service.OrderService;
import com.imooc.service.PayService;
import com.imooc.service.ProductService;
import com.imooc.utils.KeyUtil;
import com.imooc.ws.SellerWebSocket;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * FileName: OrderServiceImpl.java
 * Description: 订单服务类
 *
 * @author HuangRI(874668739 @ qq.com)
 * @version 1.0
 * @date 2020/12/17
 */
@Slf4j
@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private ProductService productService;

    @Autowired
    private OrderMasterRepository orderMasterRepository;

    @Autowired
    private OrderDetailRepository orderDetailRepository;

    @Autowired
    private PublishMessageServiceImpl publishMessageService;

    @Autowired
    private PayService payService;

    @Autowired
    private SellerWebSocket sellerWebSocket;

    @Transactional
    @Override
    public OrderDTO create(OrderDTO orderDTO) {
        log.info("创建订单");
        String orderId = KeyUtil.genUniqueKey();

        // 订单总价
        BigDecimal orderAmount = new BigDecimal(0);
        // 1、查询商品（数量、价格）
        for (OrderDetail orderDetail : orderDTO.getOrderDetailList()) {
            ProductInfo productInfo = this.productService.findOne(orderDetail.getProductId());
            if (productInfo == null) {
                throw new SellException(ResultEnum.PRODUCT_NOT_EXIST);
            }

            // 2、计算总价
            BigDecimal productAmount = productInfo.getProductPrice().multiply(new BigDecimal(orderDetail.getProductQuantity()));
            orderAmount = orderAmount.add(productAmount);

            // 3、写入订单数据库（orderMaster和orderDetail）
            orderDetail.setOrderId(orderId);
            orderDetail.setDetailId(KeyUtil.genUniqueKey());
            BeanUtils.copyProperties(productInfo, orderDetail);
            orderDetailRepository.save(orderDetail);
        }

        orderDTO.setOrderId(orderId);
        orderDTO.setOrderAmount(orderAmount);
        orderDTO.setOrderStatus(OrderStatusEnum.NEW.getCode());
        orderDTO.setPayStatus(PayStatusEnum.WAIT.getCode());
        OrderMaster orderMaster = new OrderMaster();
        BeanUtils.copyProperties(orderDTO, orderMaster);
        orderMasterRepository.save(orderMaster);

        // 4、扣库存
        List<CartDTO> cartDTOS = orderDTO.getOrderDetailList().stream()
                .map(d -> new CartDTO(d.getProductId(), d.getProductQuantity()))
                .collect(Collectors.toList());
        productService.decreaseStock(cartDTOS);

        // 发送websocket消息给卖家
        this.sellerWebSocket.sendMessage(orderDTO.getOrderId());
        return orderDTO;
    }

    @Override
    public OrderDTO findOne(String orderId) {
        log.info("查询订单[{}]", orderId);
        // 1、查询订单主表
        Optional<OrderMaster> orderMasterOptional = this.orderMasterRepository.findById(orderId);
        if (!orderMasterOptional.isPresent()) {
            // 订单不存在
            throw new SellException(ResultEnum.ORDER_NOT_EXIST);
        }

        // 2、查询订单详情表
        List<OrderDetail> orderDetails = this.orderDetailRepository.findByOrderId(orderId);
        if (CollectionUtils.isEmpty(orderDetails)) {
            throw new SellException(ResultEnum.ORDER_DETAIL_NOT_EXIST);
        }

        OrderMaster orderMaster = orderMasterOptional.get();
        OrderDTO orderDTO = new OrderDTO();
        BeanUtils.copyProperties(orderMaster, orderDTO);
        orderDTO.setOrderDetailList(orderDetails);
        return orderDTO;
    }

    @Override
    public Page<OrderDTO> findList(String buyerOpenid, Pageable pageable) {
        log.info("查询订单列表， buyerOpenid: {}", buyerOpenid);
        Page<OrderMaster> orderMasterPage = this.orderMasterRepository.findByBuyerOpenid(buyerOpenid, pageable);
        log.info("订单列表： buyerOpenid: {}， page: {}, totalElements:{}, curPageElements: {}",
                buyerOpenid, pageable.getPageNumber(),
                orderMasterPage.getTotalElements(),
                orderMasterPage.getNumberOfElements());
        return OrderMaster2OrderDTOConverter.convert(orderMasterPage);
    }

    /**
     * @param orderDTO OrderDTO
     * @return
     */
    @Override
    @Transactional
    public OrderDTO cancel(OrderDTO orderDTO) {
        log.info("取消订单");
        // 1、判断订单的状态是否为新下单，是才进行取消操作
        if (!orderDTO.getOrderStatus().equals(OrderStatusEnum.NEW.getCode())) {
            log.error("【取消订单】订单状态不正确，orderId={}, orderStatus={}",
                    orderDTO.getOrderId(), orderDTO.getOrderStatus());
            throw new SellException(ResultEnum.ORDER_STATUS_ERROR);
        }
        orderDTO.setOrderStatus(OrderStatusEnum.CANCEL.getCode());

        // 2、取消订单
        OrderMaster orderMaster = new OrderMaster();
        BeanUtils.copyProperties(orderDTO, orderMaster);
        OrderMaster updatedResult = this.orderMasterRepository.save(orderMaster);
        if (null == updatedResult) {
            log.error("【取消订单】更新失败，orderMaster={}", orderMaster);
            throw new SellException(ResultEnum.ORDER_UPDATE_FAIL);
        }

        // 3、返还库存
        List<OrderDetail> orderDetailList = orderDTO.getOrderDetailList();
        if (CollectionUtils.isEmpty(orderDetailList)) {
            log.error("【取消订单】订单中无商品详情, orderDTO={}", orderDTO);
            throw new SellException(ResultEnum.ORDER_DETAIL_EMPTY);
        }
        // 订单详情列表不为空才进行库存返回
        List<CartDTO> cartDTOs = orderDetailList.stream()
                .map(orderDetail -> new CartDTO(orderDetail.getProductId(), orderDetail.getProductQuantity()))
                .collect(Collectors.toList());
        this.productService.increaseStock(cartDTOs);

        // 4、如果支付状态为已支付，则退款
        if (PayStatusEnum.SUCCESS.getCode().equals(orderDTO.getPayStatus())) {
            log.info("【取消订单】微信退款");
            this.payService.refund(orderDTO);
        }

        // 推送微信模板消息
        this.publishMessageService.orderStatus(orderDTO);
        return orderDTO;
    }

    @Override
    @Transactional
    public OrderDTO finish(OrderDTO orderDTO) {
        log.info("完结订单");
        // 1、判断订单状态是否为新下单
        if (!OrderStatusEnum.NEW.getCode().equals(orderDTO.getOrderStatus())) {
            log.error("【完结订单】订单状态不正确，orderId={}, orderStatus={}",
                    orderDTO.getOrderId(), orderDTO.getOrderStatus());
            throw new SellException(ResultEnum.ORDER_STATUS_ERROR);
        }

        // 2、更新订单状态为完结并存库
        orderDTO.setOrderStatus(OrderStatusEnum.FINISHED.getCode());
        OrderMaster orderMaster = new OrderMaster();
        BeanUtils.copyProperties(orderDTO, orderMaster);
        OrderMaster result = this.orderMasterRepository.save(orderMaster);
        if (null == result) {
            log.error("【完结订单】更新订单失败, orderDTO={}", orderDTO);
            throw new SellException(ResultEnum.ORDER_UPDATE_FAIL);
        }

        // 推送微信模板消息
        this.publishMessageService.orderStatus(orderDTO);
        return orderDTO;
    }

    @Override
    @Transactional
    public OrderDTO paid(OrderDTO orderDTO) {
        log.info("支付订单");
        // 1、判断订单状态
        if (!OrderStatusEnum.NEW.getCode().equals(orderDTO.getOrderStatus())) {
            log.error("【支付订单】订单状态不正确，orderId={}, orderStatus={}",
                    orderDTO.getOrderId(), orderDTO.getOrderStatus());
            throw new SellException(ResultEnum.ORDER_STATUS_ERROR);
        } else if (!PayStatusEnum.WAIT.getCode().equals(orderDTO.getPayStatus())) {
            log.error("【支付订单】订单支付状态不正确，orderId={}, payStatus={}",
                    orderDTO.getOrderId(), orderDTO.getPayStatus());
            throw new SellException(ResultEnum.ORDER_PAY_STATUS_ERROR);
        }

        // 2、修改订单支付状态
        orderDTO.setPayStatus(PayStatusEnum.SUCCESS.getCode());
        OrderMaster orderMaster = new OrderMaster();
        BeanUtils.copyProperties(orderDTO, orderMaster);
        OrderMaster result = this.orderMasterRepository.save(orderMaster);

        // 3、判断保存结果
        if (null == result) {
            log.error("【支付订单】更新订单失败, orderDTO={}", orderDTO);
            throw new SellException(ResultEnum.ORDER_UPDATE_FAIL);
        }

        // 推送微信模板消息
        this.publishMessageService.orderStatus(orderDTO);
        return orderDTO;
    }

    @Override
    public Page<OrderDTO> findList(Pageable pageable) {
        Page<OrderMaster> orderMasterPage = this.orderMasterRepository.findAll(pageable);
        log.info("【查询订单列表】查询到订单列表：page: {}, totalElements:{}, curPageElements: {}",
                pageable.getPageNumber(),
                orderMasterPage.getTotalElements(),
                orderMasterPage.getNumberOfElements());
        return OrderMaster2OrderDTOConverter.convert(orderMasterPage);
    }
}
